import './index.less';
import { Grid } from 'react-vant';
import { staticModeList, deviceId } from '../../utils/staticData';
import { useEffect, useState, useRef } from 'react';
import SvgIcon from '../../components/SvgIcon/index';
import { debounce } from '../../utils/utils';
import useStore from '../../store/index';

export default function Mode({ onModeChange }: any) {
  const Hejia = (window as any).Hejia;
  const { startLoop, stopLoop, info } = useStore();

  const { mode, isOnline, state, fault, prompt } = info
  const [selectedItemId, setSelectedItemId] = useState<number | null>(null);

  // 定时器变量
  const timeoutId = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (Date.now() - lastSetTime.current < 5000) {
      return;
    }
    setSelectedItemId(mode);
  }, [mode]);

  const lastSetTime = useRef<number>(0);

  const handleModeClick = (id: number): void => {
    if (id === selectedItemId) return;
    // 记录当前设置的时间
    lastSetTime.current = Date.now();

    stopLoop();
    clearTimeout(timeoutId.current as NodeJS.Timeout);

    onModeChange(id);
    setSelectedItemId(id);

    debounce(() => {
      Hejia.setControlParam(
        {
          // deviceId,
          parameters: {
            param: [
              {
                name: 'mode',
                content: id
              }
            ]
          }
        },
        function () {
          // success, no response
          timeoutId.current = setTimeout(() => {
            startLoop();
          }, 2000);
          console.log('success');
        },
        function (msg: string, obj: any) {
          startLoop()
          console.log(msg + obj.resultCode + obj.resultCodeMessage);
        }
      );
    }, 300)();
  };

  return (
    <div className="mode">
      <div
        className={
          !isOnline || fault > 0 || [1, 2].includes(state) || prompt > 0
            ? 'offline-title'
            : 'title'
        }
      >
        模式
      </div>
      <div className="mask-wapper">
        {(!isOnline || fault > 0 || prompt > 0 || [1, 2].includes(state)) && (
          <div className="mask"></div>
        )}
        <Grid columnNum={4} border={false}>
          {staticModeList.map(item => (
            // react传递参数必须是回调函数
            <Grid.Item key={item.id} onClick={() => handleModeClick(item.id)}>
              <div
                className={`item ${item.id === selectedItemId ? 'active' : ''}`}
              >
                <SvgIcon
                  name={`${item.svg}`}
                  size="48"
                  color={`${item.id === selectedItemId
                    ? 'var(--primary-color)'
                    : 'var(--title-color)'
                    }`}
                />
                <span
                  style={{
                    color:
                      item.id === selectedItemId
                        ? 'var(--primary-color)'
                        : 'var(--title-color)'
                  }}
                >
                  {item.title}
                </span>
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    </div >
  );
}
